<template>
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px  " @click="addItem">新增</el-button>
        <el-input v-model="search" placeholder="请输入用户名"
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable></el-input>
        <el-input v-model="searchTel" placeholder="请输入手机号"
                  style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable></el-input>
        <!--对应按键-->
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
        </el-button>
        <!--<el-button type="success" @click="importData">导入</el-button>-->
        <!--<el-button type="success" @click="exportData">导出</el-button>-->
    </div>
    <!--主表格 分页-->
    <div>
        <el-table :data="tableData" :row-style="{ height: '77px' }" border
            style="width: calc(100vw - 240px);height: 75vh;margin-top: 20px;font-size: 15px;">
            <el-table-column prop="username" label="用户名" align="center" width="150" />
            <el-table-column prop="sex" label="性别" align="center" width="90">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.sex === 0">男</el-tag>
                    <el-tag type="success" v-else-if="scope.row.sex === 1">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" align="center" width="90" />
            <el-table-column prop="telephone" label="手机号码" align="center" width="180" />
            <el-table-column prop="photo" label="头像" align="center" width="180">
                <template v-slot="scope">
                    <div @click="openPreview(scope.row.photo)" style="cursor: pointer;">
                        <el-image style="width: 100px; height: 100px" :src="scope.row.photo"></el-image>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" align="center" width="180" />
            <el-table-column prop="department" label="部门" align="center" width="180" />
            <el-table-column prop="section" label="科室" align="center" width="180" />
            <el-table-column prop="email" label="邮箱" align="center" width="180" />
            <el-table-column prop="createTime" label="创建时间" align="center" width="200px" />
            <el-table-column prop="updateTime" label="修改时间" align="center" width="200px" />
            <el-table-column label="操作" fixed="right" align="center" width="300">
                <template v-slot="scope">
                    <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                    <el-button :disabled="scope.row.id === 1" type="danger" size="small" icon="Delete"
                        @click="deleteItem(scope.row.id)">删除
                    </el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="resetPWD(scope.row.id)">重置密码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!--分页栏-->
    <div style="margin-top: 10px">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog :close-on-click-modal="false" title="培训负责人操作" v-model="dialogVisible" width="560" @close="reset('form')">
        <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="请输入年龄(必须为数字)" autocomplete="off" oninput="this.value = this.value.replace(/[^0-9]/g, '')"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
                <el-select v-model="form.roleIds" multiple filterable style="width: 185px" placeholder="请选择用户角色">
                    <el-option v-for="item in roleOptions" :key="item.id" :label="item.rolename" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" clearable placeholder="请选择性别" style="width: 185px">
                    <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入手机号码" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" placeholder="请输入单位" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="部门" prop="department">
                <el-input v-model="form.department" placeholder="请输入部门" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="科室" prop="section">
                <el-input v-model="form.section" placeholder="请输入科室" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input style="width: 185px" v-model="form.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="photo">
                <el-upload class="avatar-uploader" :before-upload="checkFileType" :action="'/api/files/upload'"
                    :on-success="photoHandleSuccess" :on-error="photoHandleError" :show-file-list="false">
                    <img width="100" height="100" v-if="form.photo" :src="form.photo" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset('form')">取消</el-button>
                <el-button type="primary" @click="submitForm('form')">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <ImagePreview ref="preview" :imageUrl="currentPreviewImage" />
</template>
<script>
import request from "~/utils/request.js";
import ImagePreview from '~/pages/ImagePreview.vue';

export default {
    components: {
        ImagePreview
    },
    data() {
        return {
            dialogImportVisible: false,
            dialogVisible: false, // 控制对话框显示
            form: {}, // 编辑表单数据
            roleOptions: [
                { id: 1, rolename: '管理员' },
                { id: 2, rolename: '培训负责人' },
                { id: 3, rolename: '培训讲师' },
            ],
            sexOptions: [
                { value: 0, label: '男' },
                { value: 1, label: '女' },
            ],
            //分页设置
            tableData: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            search: '',
            searchTel: '',
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                roleIds: [
                    { required: true, message: '请选择用户角色', trigger: 'blur' },
                ],
                telephone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                ],
            },
            currentPreviewImage: '' // 当前预览的图片URL
        }
    },
    created() {
        this.load()
        // this.getRoleOptions()
    },
    methods: {
        load() {
            request.get("/user/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.search + "&telephone=" + this.searchTel + "&roleId=" + 2).then(res => {
                if (res.code === '200') {
                    this.tableData = res.data.records
                    this.total = res.data.total
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        getRoleOptions() {
            request.get("/role/all").then(res => {
                if (res.code === '200') {
                    this.roleOptions = res.data
                }
            })
        },
        // 确认重置密码
        resetPWD(scope) {
            this.$confirm('是否确定重置密码?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/user/resetPwd?id=" + scope).then(res => {
                    if (res.code === '200') {
                        this.$notify({
                            title: '重置成功',
                            message: '用户密码重置成功，当前密码为123456'
                        });
                    } else {
                        this.$message.error("删除失败" + res.msg)
                    }
                })
            });
        },
        editItem(item) {
            Object.assign(this.form, item)
            this.dialogVisible = true
        },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/user/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        // 提交
        submitForm(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    request.post("/user/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = {};
            this.$refs[val].clearValidate();
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },
        checkFileType(file) {
            const maxSize = 1024 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.warning('文件大小超过1GB限制!');
                return false;
            }
            return true;
        },
        photoHandleSuccess(response) {
            console.log(response)
            this.form.photo = `/api/file/download/${response}`
            this.$message.success('上传成功');
        },
        photoHandleError() {
            this.$message.error("上传文件失败")
        },
        openPreview(imageUrl) {
            if (!imageUrl) return;
            this.currentPreviewImage = imageUrl;
            this.$nextTick(() => {
                this.$refs.preview.open();
            });
        }
    }
}
</script>
<style></style>
